package Lib

import (
	"fmt"
	"myblogs/app/variable"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

// var db *sqlx.DB

func GetMysqlDbClient() (*sqlx.DB, error) {
	if len(variable.DbHost) == 0 {
		variable.DbHost = "mysql.local.cc"
	}
	if len(variable.DbPort) == 0 {
		variable.DbPort = "3306"
	}
	if len(variable.DbUser) == 0 {
		variable.DbUser = "root"
	}
	if len(variable.DbPassword) == 0 {
		variable.DbPassword = "123456"
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/myzx-admin?charset=utf8mb4&parseTime=True", variable.DbUser, variable.DbPassword, variable.DbHost, variable.DbPort)
	// dsn := "root:123456@tcp(mysql.local.cc:3306)/myzx-admin?charset=utf8mb4&parseTime=True"
	// dsn := "root:VEfRDHzYnd8pUuA5@tcp(127.0.0.1:5616)/myzx-admin?charset=utf8mb4&parseTime=True"
	// 也可以使用MustConnect连接不成功就panic
	db, err := sqlx.Connect("mysql", dsn)
	if err != nil {
		fmt.Printf("connect DB failed, err:%v\n", err)
		return nil, err
	}
	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	return db, nil
}
